package com.xmg.controller;

import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author: mazhongqing
 * @Date: 2020/11/4 14:03
 * 全局异常捕获类，捕获异常，然后自定义数据格式返回给用户
 * @RestControllerAdvice-->RestController
 * @ControllerAdvice-->Controller
 */
@RestControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO<String> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        //从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        //拿到错误信息进行返回
        return new ResultVO<>(ResultEnum.VALIDATE_FAILED,objectError.getDefaultMessage());
    }

    @ExceptionHandler(APIException.class)
    public ResultVO<String> APIExceptionHandler(APIException e){
        return new ResultVO<>(ResultEnum.FAILED,e.getMsg());
    }
}
